<template>
  <div class="login">
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">cgClass后台管理系统</h3>
      <el-form-item prop="username">
        <el-input v-model.trim="loginForm.username" type="text" size="large" auto-complete="off" placeholder="账号">
          <template #prefix>
            <span class="iconfont icon-mobile-phone"></span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model.trim="loginForm.password" type="password" size="large"  show-password auto-complete="off" placeholder="密码"
          @keyup.enter="handleLogin">
          <template #prefix>
            <span class="iconfont icon-password"></span>
          </template>
        </el-input>
      </el-form-item>
      <!-- 验证码结构 -->
      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input v-model.trim="loginForm.code" size="large" auto-complete="off" placeholder="验证码" style="width: 63%"
          @keyup.enter="handleLogin">
          <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img" />
        </div>
      </el-form-item>
      <el-checkbox v-model="rememberMe" style="margin: 0px 0px 25px 0px">记住密码</el-checkbox>
      <el-form-item style="width: 100%">
        <el-button :loading="loading" size="large" type="primary" style="width: 100%" @click.prevent="handleLogin">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 学院选择的弹窗 -->

    <el-dialog class="schoolDialog" v-model="dialogVisible" title="" width="400">
      <h2>请选择要进入的学院</h2>
      <div class="schList">
        <el-button @click="onCollegeBtn(item, index)" :type="btnIdx == index ? 'primary' : ''" :icon="School"
          v-for="(item, index) in collegeArr">{{ item.name }}</el-button>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="onConfirm" type="primary" :disabled="isDisabled">
            确认
          </el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getCodeImg, login } from "@/api/login";
import Cookies from "js-cookie";
import { School } from "@element-plus/icons-vue";
import { cgyunlogin} from "@/api/login";
// 密码加密和解密
import { encrypt, decrypt } from "@/utils/jsencrypt";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/store/modules/user.js";
import { aviCollege } from "@/api/user";
const btnIdx = ref(null);
const isDisabled = ref(true);
const dialogVisible = ref(false);
const { proxy } = getCurrentInstance();
// 学院数组
const collegeArr = ref([]);
const loginForm = ref({
  username: Cookies.get("username") ? Cookies.get("username") : "",
  password: Cookies.get("password") ? decrypt(Cookies.get("password")) : "",
  code: "",
  uuid: "",
});

const rememberMe = ref(false);
const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }],
};
const codeUrl = ref("");
const loading = ref(false);

// 学院数据
const schListData = ref(["传媒学院", "泰山学院"]);
// 验证码开关
const captchaEnabled = ref(true);
const router = useRouter();
const route = useRoute()
// 点击登陆的函数
function handleLogin() {
  proxy.$refs.loginRef.validate((valid) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (rememberMe.value) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), {
          expires: 30,
        });
        Cookies.set("rememberMe", rememberMe.value, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      // 调用action的登录方法
      // 这里要调用登陆接口，登陆接口在api-login.js传递登陆用户的数据  登陆成功将loadding状态改为false,并且跳转到home页面
      const [username, password, code, uuid] = [
        loginForm.value.username,
        loginForm.value.password,
        loginForm.value.code,
        loginForm.value.uuid,
      ];

      login(username, password, code, uuid).then((res) => {
        if (res.user) {
          if (!res.user.roles.length && !res.user.is_super) {
            ElMessage.error("您不在角色分组里,请联系超级管理员");
            loading.value = false;
            return;
          }
          loading.value = false;
          useUserStore().token = res.user.token;
          useUserStore().roles = res.user.roles;
          useUserStore().userName = res.user.username;
          useUserStore().is_super = res.user.is_super;
          useUserStore().tenant_id = res.user.tenant_id;
          useUserStore().role_top = res.user.role_top;
          
          // 如果是超级管理员，直接设置角色为管理组并进入系统
          if (res.user.is_super) {
            useUserStore().rolesName = "管理组";
            router.push({ path: "/" });
            ElMessage({
              message: "登陆成功",
              type: "success"
            });
            return;
          }
          
          // 如果角色组里面有角色，则选择第一个角色
          if (res.user.role_top.length > 0) {
            useUserStore().college_id = res.user.role_top[0].id;
          }

          // 登陆成功判断有没有支持的学院
          aviCollege().then((data) => {
            collegeArr.value = data;
            if (!data.length || data.length == 1) {
              router.push({ path: "/" });
              ElMessage({
                message: "登陆成功",
                type: "success",
              });
              useUserStore().loginTime = Date.now();

              let roles = useUserStore().roles.find(item => item.name == "老师组")
              if (roles) {
                useUserStore().rolesName = roles.name
              } else {
                if (!useUserStore().roles.length) {
                  useUserStore().rolesName = "未分组"
                  return next('/login');
                } else {
                  useUserStore().rolesName = useUserStore().roles[0].name
                }
              }
            } else {
              dialogVisible.value = true;
            }
          });
        } else {          
          // 处理错误情况
          ElMessage({
            message: res.response.data,
            type: "error",
          });
          loading.value = false;
          getCode();
          loginForm.value.code = "";
        }
      });
    }
  });
}
// 获取验证码

const getCode = () => {
  getCodeImg().then((res) => {
    captchaEnabled.value = res.enable === undefined ? true : res.enable;
    if (captchaEnabled.value) {
      codeUrl.value = res.img;
      loginForm.value.uuid = res.uuid;
    }
  });
};
getCode();
// 选择学院事件
const onCollegeBtn = (item, idx) => {
  useUserStore().college_id = item.id;
  btnIdx.value = idx;
  isDisabled.value = false;
};

// 点击选择学院弹窗中的确定
const onConfirm = () => {
  router.push({ path: "/" });
  ElMessage({
    message: "登陆成功",
    type: "success",
  });
  
  // 如果是超级管理员，直接设置为管理组
  if (useUserStore().is_super) {
    useUserStore().rolesName = "管理组";
    return;
  }
  
  let roles = useUserStore().roles.find(item => item.name == "老师组")
  if (roles) {
    useUserStore().rolesName = roles.name
  } else {
    if (!useUserStore().roles.length) {
      useUserStore().rolesName = "未分组"
      return next('/login');
    } else {
      useUserStore().rolesName = useUserStore().roles[0].name
    }
  }
};



// cgyun对接cgClass
onMounted(()=>{

console.log('code参数',route.query.code)
// 请求cgyun/login post请求 传递参数code

if(route.query.code){

  cgyunlogin(route.query.code).then(res=>{
  if (res.user) {
      if (!res.user.roles.length && !res.user.is_super) {
        ElMessage.error("您不在角色分组里,请联系超级管理员");
        loading.value = false;
        return;
      }   
      useUserStore().token = res.user.token;
      useUserStore().roles = res.user.roles;
      useUserStore().userName = res.user.username;
      useUserStore().is_super = res.user.is_super;
      useUserStore().tenant_id = res.user.tenant_id;
      useUserStore().role_top = res.user.role_top;
      useUserStore().loginTime = Date.now();
      let roles = useUserStore().roles.find(item => item.name == "老师组")
          if (roles) {
            useUserStore().rolesName = roles.name
          } else {
            if (!useUserStore().roles.length) {
              useUserStore().rolesName = "未分组"
              return next('/login');
            } else {
              useUserStore().rolesName = useUserStore().roles[0].name
            }
          }
      router.push({ path: "/" });
          ElMessage({
            message: "登陆成功",
            type: "success",
          });
      // 如果是超级管理员，直接设置角色为管理组并进入系统
      if (res.user.is_super) {
        useUserStore().rolesName = "管理组";
        router.push({ path: "/" });
        ElMessage({
          message: "登陆成功",
          type: "success"
        });
        return;
      } 
      // 如果角色组里面有角色，则选择第一个角色
      if (res.user.role_top.length > 0) {
        useUserStore().college_id = res.user.role_top[0].id;
      }
    } else {          
      // 处理错误情况
      ElMessage({
        message: res.response.data,
        type: "error",
      });

    }
  console.log(res);
})
}

})


</script>

<style lang="scss" scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-size: cover;
  background-image: url("../assets/images/login-background.jpg");
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 40px;

    input {
      height: 40px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 40px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 36px;
  padding-left: 12px;
}

.schoolDialog {
  h2 {
    color: #000;
    text-align: center;
  }

  .schList {
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    padding: 30px 0 20px;

    .el-button {
      width: 80%;
      height: 40px;
      margin-left: 0;
      margin-top: 10px;
      display: flex;
      align-items: center;
    }
  }
}
</style>
